<template>
  <grid title="个人设置">
    <el-form ref="form"
             style="text-align: left; width:1000px"
             label-width="100px"
             @submit.native.prevent="onFormSubmit"
             :model="form"
             :rules="rules">
      <el-form-item label="昵称"
                    prop="nick_name">
        <el-input v-model="form.nick_name"
                  placeholder="请输入昵称，限8个字"
                  clearable></el-input>
      </el-form-item>
      <el-form-item label="简介"
                    prop="signature">
        <el-input v-model="form.signature"
                  placeholder="请输入个人简介，限50个字"
                  clearable></el-input>
      </el-form-item>
      <el-form-item label="头像"
                    prop="avatar">
        <image-input type="avatar"
                     v-model="form.avatar"></image-input>
        <p class="caption">注：建议上传尺寸60*60的 PNG图</p>
      </el-form-item>
      <el-form-item label="浮窗">
        <el-checkbox v-model="form.visibility">开启</el-checkbox>
        <p class="caption">勾选后将在网站右侧显示站长信息</p>
      </el-form-item>
      <el-form-item label="联系我">
        <el-checkbox v-model="form.contact">开启</el-checkbox>
        <p class="caption">勾选后打开网站将显示联系我按钮</p>
      </el-form-item>
      <el-form-item>
        <el-button type="primary"
                   native-type="submit">保存</el-button>
      </el-form-item>
    </el-form>
  </grid>
</template>

<script>
import imageInput from '@/components/image-input'
import { mapActions, mapGetters } from 'vuex'
import { deepCopy } from '@/utils/common'

export default {
  title () {
    return '个人设置'
  },
  data () {
    return {
      form: {
        nick_name: undefined,
        signature: undefined,
        avatar: [],
        contact: false,
        visibility: false
      },
      rules: {
        nick_name: [
          { required: true, message: '昵称不能为空' },
          { max: 8, message: '最长8个字' }
        ],
        signature: [
          { max: 50, message: '最长50个字' }
        ],
        avatar: [
          { required: true, message: '头像 不能为空' }
        ]
      }
    }
  },
  components: {
    imageInput
  },
  async asyncData ({ store, route }) {
    const { query } = route;
    return store.dispatch('setting/view', 'personal')
  },
  computed: {
    ...mapGetters('setting', ['personal'])
  },
  async mounted () {
    this.$nextTick(() => {
      this.form = deepCopy(this.personal)
      this.form.avatar = this.form.avatar !== '{}' ? [this.form.avatar] : []
    })
  },
  methods: {
    ...mapActions('setting', ['updatePersonal']),
    async onFormSubmit () {
      await this.$refs.form.validate()
      let avatar = {}
      if (this.form.avatar.length) {
        const { avatar: [{ id, url }] } = this.form
        avatar = { id, url }
      }
      const params = { ...this.form, avatar }
      await this.updatePersonal(params)
      this.$message.success('保存成功')
    }
  }
}
</script>
